package com.devin.service.Impl;

import com.devin.dao.UserMapper;
import com.devin.pojo.Role;
import com.devin.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("myUserDetailsService")
@Transactional
public class MyUserDetialsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("==============================");
        UserInfo user = userMapper.getUser(s);
        User user1 = new User(user.getUsername(),user.getPassword(),user.getStatus()==1?true:false,true,true,true,getAuthorties(user.getRoles()));
        return user1;
    }

    private List<SimpleGrantedAuthority> getAuthorties(List<Role> roles){
        ArrayList<SimpleGrantedAuthority> authorties = new ArrayList<>();
        for(Role role:roles){
            authorties.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return authorties;
    }
}
